package com.tianqu.tms.www.member.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.webservice.weichat.api.MobileMessage;
import com.tianqu.tms.core.webservice.weichat.api.PullingExecutor;
import com.tianqu.tms.core.webservice.weichat.api.rpc.MemberAddBo;
import com.tianqu.tms.entity.CarImage;
import com.tianqu.tms.entity.Member;
import com.tianqu.tms.entity.Sequence;
import com.tianqu.tms.entity.User;
import com.tianqu.tms.www.member.viewhelper.MemberInputViewHelper;

/**
 * 
 * 商户信息录入结果页
 * 
 * @author tianshifu
 * 
 */
public class MemberCreationResultController extends TmsController {

	private Logger logger = Logger.getLogger(MemberCreationResultController.class);

	private static final String IMGLIST = "imgList";// 图片list
	private static final String SYSPATH = "sysPath";//
	public static final String FLOORSFLAG = "floorsflag";

	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();

		// 添加事务提交异常捕获
		try {
			controller.begin();

			// 从uc中获取会员信息
			MemberInputViewHelper viewhelp = (MemberInputViewHelper) uc.getAttribute(TmsConstants.VIEWHELP);
			viewhelp.setBackFlag(2);
			uc.removeAttribute(TmsConstants.VIEWHELP);// 清空uc

			// 将viewhelp信息set到entity中，两部分，会员基本信息表和用户表
			Member memEntity = new Member();
			memEntity = setMemberFromView(memEntity, viewhelp);
			// 将图片信息set到entity中
			// 从mapList中取出图片信息set到viewhelp中
			List<CarImage> imgList = new ArrayList<CarImage>();
			if (uc.getAttribute(IMGLIST) != null) {
				imgList = (List<CarImage>) uc.getAttribute(IMGLIST);
			}
			if (imgList != null) {
				// 将list中的数据取出set到viewhelp中
				for (int i = 0; i < imgList.size(); i++) {
					CarImage entity = (CarImage) imgList.get(i);
					if (entity.getImgKey().equals(TmsConstants.ONE)) {
						memEntity.setOrgPhoto(entity.getImgPath());
					}
					if (entity.getImgKey().equals(TmsConstants.TWO)) {
						memEntity.setBusinessPhoto(entity.getImgPath());
					}
					if (entity.getImgKey().equals(TmsConstants.THREE)) {
						memEntity.setCardPhoto(entity.getImgPath());
					}
					if (entity.getImgKey().equals(TmsConstants.FIVE)) {
						memEntity.setMemberZipCode(entity.getImgPath());
					}
				}
			}				
			TmsUserProfile profile = uc.getUserProfile();
			memEntity.setUpdateUserId(profile.getUniqueId());
			memEntity.setInsertUserId(profile.getUniqueId());
			String sysPath = (String) uc.getAttribute(SYSPATH);
			Sequence sequence = Sequence.getInstance();
			String memberId = "";
			memberId = sequence.getSerial(4);
			memEntity.setMemId(Integer.parseInt(memberId));
			memEntity.setMemName(memberId);

			// 执行会员添加操作
			memEntity.insetMemberInfoByEntity(memEntity, sysPath);

			// 执行用户表添加操作，给会员默认值
			User user = new User();
			user = setUserFormView(user, viewhelp);
			user.setUpdateUserId(profile.getUniqueId());
			user.setInsertUserId(profile.getUniqueId());
			user.setUcId("11");// 默认为系统会员

			user.saveUserInfo(user,2);
			
			uc.removeAttribute(IMGLIST);
			logger.debug(this.getClass().getName() + "#execute was completed.");
			controller.commit();
			//微信同步
//			UserManager userApi = UserManagerImpl.create();
//			//会员ID、公司名称、积分卡编号、积分卡卡号、登录名、车位总数、
//			userApi.memberAdd(memberId, memEntity.getRealName(), memEntity.getAccessCardId(), memEntity.getAccessCardNo(), memEntity.getCarPort());
			
			MobileMessage message = new MobileMessage();
			message.putValue("MemberId", memberId);
			message.setMessage("TMS商户添加调用[商户添加]接口失败,商户ID为#MemberId#");
			
			MemberAddBo api = new MemberAddBo();
			api.setMobileMessage(message);
			api.setMemberId(memberId);
			api.setRealName(memEntity.getRealName());
			api.setShortName(memEntity.getShortName());
			api.setMarketNo(TmsConstants.MARKET_NO);
			Member member = memEntity.findMemberInfoByMemId(memberId);
			if(StringUtils.isNotEmpty(member.getRealNamePy()))api.setRealNamePy(memEntity.getRealNamePy());
			PullingExecutor.getInstance().submit(api);
			
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

	}

	/**
	 * 将页面信息set到entity中用于添加操作
	 * 
	 * @return
	 */
	private Member setMemberFromView(Member entity, MemberInputViewHelper view) {		
		//商户名称
		entity.setRealName(view.getRealName());
		//商户短名
		entity.setShortName(view.getShortName());
		//商户名称拼音
		entity.setRealNamePy(view.getRealNamePy());
		//联系人
		entity.setContactOwner(view.getContactOwner());
		//联系人电话
		entity.setContactPhone(view.getContactPhone());
		//法人姓名
		entity.setLegal(view.getLegal());
		//法人电话
		entity.setPhone(view.getPhone());
		//法人性别
		if (view.getRegisteredCapital() == null
				|| "".equals(view.getRegisteredCapital())) {
			entity.setRegisteredCapital(0);
		} else {
			entity.setRegisteredCapital(Integer.parseInt(view.getRegisteredCapital()));
		}
		//法人身份证号
		entity.setCardNo(view.getCardNo());
		//法人生日
		entity.setSettlePhone(view.getSettlePhone().replaceAll("-", ""));
		//法人地址
		entity.setOrgNo(view.getOrgNo());
		//备注
		entity.setCarPortInstr(view.getCarPortInstr());
		//用户名
		entity.setUserId(view.getUserId());

		return entity;
	}

	/**
	 * 将viewhelp中的数据set到user中进行添加
	 * 
	 */
	private User setUserFormView(User entity, MemberInputViewHelper view) {

		entity.setLoginId(view.getUserId());
		entity.setRealName(view.getRealName());
		entity.setPassword(view.getPassword());
		return entity;
	}
}
